import java.util.concurrent.BlockingDeque;

public class Consumer implements Runnable {
	private final BlockingDeque<Integer>[] dequeues;
	private final int index;
	private int factorizedCount = 0;
	private int stolenCount = 0;

	public Consumer(BlockingDeque<Integer>[] dequeues, int index) {
		this.dequeues = dequeues;
		this.index = index;
	}

	public void run() {
		outer: while (true) {
			Integer number = dequeues[index].pollFirst();
			if (number != null) {
				indexFile(number, false, -1);
			} else {
				for (int i = 0; i < dequeues.length; i++) {
					number = dequeues[i].pollLast();
					if (number != null) {
						indexFile(number, i != index, i);
						continue outer;
					}
				}
			}
			if (Thread.currentThread().isInterrupted()) {
				boolean allEmpty = true;
				for (int i = 0; i < dequeues.length; i++) {
					if (!dequeues[i].isEmpty()) {
						allEmpty = false;
						break;
					}
				}
				if (allEmpty) {
					break;
				}
			}
		}
		System.out
				.printf("Consumer-%d finished working (factorized %d numbers, including %d stolen ones, percent stolen = %d).\n",
						index, factorizedCount, stolenCount,
						factorizedCount == 0 ? 0 : (stolenCount * 100)
								/ factorizedCount);
	}

	@SuppressWarnings("unused")
	public void indexFile(Integer number, boolean stolen, int stolenFrom) {
		Factorizator f = new Factorizator(new int[1]);
		int factors[] = f.expensiveFactorize(number);

		// System.out.println(number + " => " + Arrays.toString(factors));

		factorizedCount++;
		if (stolen && stolenFrom != index) {
			stolenCount++;
		}
	};
}